import { useState, useEffect, useCallback } from 'react';
import { message } from 'antd';

/**
 * 通用异步数据获取Hook
 * @param {Function} fetchFunction - 数据获取函数
 * @param {Object} options - 配置选项
 * @param {Array} dependencies - 依赖数组
 * @returns {Object} { data, loading, error, refetch, setData }
 */
export const useAsyncData = (
  fetchFunction,
  options = {},
  dependencies = []
) => {
  const {
    immediate = true,
    initialData = null,
    onSuccess,
    onError,
    showErrorMessage = true,
    errorMessage = '数据加载失败'
  } = options;

  const [data, setData] = useState(initialData);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  const fetchData = useCallback(async (...args) => {
    try {
      setLoading(true);
      setError(null);
      
      const result = await fetchFunction(...args);
      
      setData(result);
      
      if (onSuccess) {
        onSuccess(result);
      }
      
      return result;
    } catch (err) {
      console.error('useAsyncData error:', err);
      setError(err);
      
      if (showErrorMessage) {
        message.error(err.message || errorMessage);
      }
      
      if (onError) {
        onError(err);
      }
      
      throw err;
    } finally {
      setLoading(false);
    }
  }, [fetchFunction, onSuccess, onError, showErrorMessage, errorMessage]);

  const refetch = useCallback((...args) => {
    return fetchData(...args);
  }, [fetchData]);

  useEffect(() => {
    if (immediate) {
      fetchData();
    }
  }, dependencies);

  return {
    data,
    loading,
    error,
    refetch,
    setData
  };
};

/**
 * 分页数据获取Hook
 * @param {Function} fetchFunction - 数据获取函数
 * @param {Object} options - 配置选项
 * @returns {Object} 分页数据和操作方法
 */
export const usePaginatedData = (
  fetchFunction,
  options = {}
) => {
  const {
    pageSize = 10,
    immediate = true,
    ...asyncOptions
  } = options;

  const [pagination, setPagination] = useState({
    current: 1,
    pageSize,
    total: 0
  });

  const [filters, setFilters] = useState({});
  const [sorter, setSorter] = useState({});

  const fetchData = useCallback(async (params = {}) => {
    const requestParams = {
      page: pagination.current,
      limit: pagination.pageSize,
      ...filters,
      ...sorter,
      ...params
    };

    const result = await fetchFunction(requestParams);
    
    // 假设返回格式为 { data: [], pagination: { total, current, pageSize } }
    if (result.pagination) {
      setPagination(prev => ({
        ...prev,
        ...result.pagination
      }));
    }
    
    return result.data || result;
  }, [fetchFunction, pagination.current, pagination.pageSize, filters, sorter]);

  const { data, loading, error, refetch } = useAsyncData(
    fetchData,
    { ...asyncOptions, immediate },
    [pagination.current, pagination.pageSize, filters, sorter]
  );

  const handleTableChange = useCallback((paginationConfig, filtersConfig, sorterConfig) => {
    // 处理分页变化
    if (paginationConfig) {
      setPagination(prev => ({
        ...prev,
        current: paginationConfig.current,
        pageSize: paginationConfig.pageSize
      }));
    }

    // 处理筛选变化
    if (filtersConfig) {
      setFilters(filtersConfig);
    }

    // 处理排序变化
    if (sorterConfig) {
      const newSorter = {};
      if (sorterConfig.field && sorterConfig.order) {
        newSorter.sortField = sorterConfig.field;
        newSorter.sortOrder = sorterConfig.order === 'ascend' ? 'asc' : 'desc';
      }
      setSorter(newSorter);
    }
  }, []);

  const resetPagination = useCallback(() => {
    setPagination(prev => ({
      ...prev,
      current: 1
    }));
  }, []);

  const updateFilters = useCallback((newFilters) => {
    setFilters(newFilters);
    resetPagination();
  }, [resetPagination]);

  return {
    data,
    loading,
    error,
    refetch,
    pagination,
    filters,
    sorter,
    handleTableChange,
    updateFilters,
    resetPagination
  };
};

/**
 * 搜索数据Hook
 * @param {Function} searchFunction - 搜索函数
 * @param {Object} options - 配置选项
 * @returns {Object} 搜索数据和操作方法
 */
export const useSearchData = (
  searchFunction,
  options = {}
) => {
  const {
    debounceMs = 300,
    minLength = 1,
    ...asyncOptions
  } = options;

  const [searchTerm, setSearchTerm] = useState('');
  const [debouncedSearchTerm, setDebouncedSearchTerm] = useState('');

  // 防抖处理
  useEffect(() => {
    const timer = setTimeout(() => {
      setDebouncedSearchTerm(searchTerm);
    }, debounceMs);

    return () => clearTimeout(timer);
  }, [searchTerm, debounceMs]);

  const fetchData = useCallback(async () => {
    if (!debouncedSearchTerm || debouncedSearchTerm.length < minLength) {
      return [];
    }
    return await searchFunction(debouncedSearchTerm);
  }, [searchFunction, debouncedSearchTerm, minLength]);

  const { data, loading, error, refetch } = useAsyncData(
    fetchData,
    { ...asyncOptions, immediate: false },
    [debouncedSearchTerm]
  );

  useEffect(() => {
    if (debouncedSearchTerm && debouncedSearchTerm.length >= minLength) {
      refetch();
    }
  }, [debouncedSearchTerm, minLength, refetch]);

  const clearSearch = useCallback(() => {
    setSearchTerm('');
  }, []);

  return {
    data,
    loading,
    error,
    searchTerm,
    setSearchTerm,
    clearSearch,
    refetch
  };
};

export default useAsyncData;